'use strict'

define(['jquery', 'bootstrap', 'select2', 'validate', 'validate.en', 'koala-search', 'shiftform', 'modalSearch',
                'datetimepicker', 'datetimepickerCN'], function($, validate) {
  return {
        
    init: function() {
      this.initPage();
      this.initShipment();
      this.initLoadPlace();
      this.initVehicle();
      this.initEmployee();
      this.triggerModalSearch();
    },
  
    initPage: function() {
      	
      $(document).find('form').bind('reset', function(e){
        $(this).find(".select2").select2("val", "");
    	})
          
      $(document).find('form').bt_validate();
      
      $('select[name="organizationId"]').select2({
        theme: "classic",
        placeholder : '请选择',
        minimumResultsForSearch : -1,
        allowClear : true,
      });
      
      $('select[name="transType"]').select2({
        theme: "classic",
        placeholder : '请选择',
        minimumResultsForSearch : -1,
        allowClear : true,
      });
      
      $('select[name="accomplishConfirm"]').select2({
        theme: "classic",
        placeholder : '请选择',
        minimumResultsForSearch : -1,
        allowClear : true,
      });

      $('.date').datetimepicker({
        format: 'yyyy-mm-dd',
        autoclose: true,
        language: 'zh-CN',
        todayBtn: 'linked',
        startDate: '${today}',
        todayHighlight: true,
        pickerPosition: 'bottom-right',
        minView: 'month'
      });
      
    },
    
    initShipment: function() {
      
      $(document).on('blur', 'input[name="loadNumber"]', function() {
        
        var $loadNumber = $('input[name="loadNumber"]');
        var $shipmentGroupId = $('input[name="shipmentGroupId"]');
        var loadNumberText = $loadNumber.val().trim();
        
        // 1. check parameter is valid
        if (!loadNumberText) {
          $loadNumber.val('');
          return;
        }
        
        var organizationId = $('[name="organizationId"]').val();
        if (!organizationId) {
          $loadNumber.show_err_tooltip('请选择公司');
          return;
        }
        
        // 2. request
        $.ajax({
          'url': window.__CTX__.root + "/shipments/query",
          'data': {
            'loadNumber': loadNumberText,
            'orgIds': organizationId
          }
        }).done(function(res) {
          
          res = typeof res === 'String' ? JSON.parse(res) : res;
          if (res.code === '0') {
            
            $shipmentGroupId.val(res.data.loadGroupNumber);
            
          } else {
            $loadNumber.val('');
            $shipmentGroupId.val('');
            $loadNumber.show_err_tooltip(res.message);
          }
          
        }).fail(function() {
          $loadNumber.show_err_tooltip('查询失败');
        });
        
      });
      
    },
    
    initLoadPlace: function() {
      
      $('[data-target="#modal-search-fromLoadPlace"]').modalsearch({
            url: window.__CTX__.root + '/load-places/query',
            tableColumns: ['出发地代码', '出发地名称'],
            tableValues: ['code', 'name'],
            displayValues: ['code', 'name'],
            values: ['id']
      });
      
      $('[data-target="#modal-search-toLoadPlace"]').modalsearch({
            url: window.__CTX__.root + '/load-places/query',
            tableColumns: ['到达地代码', '到达地名称', 'id'],
            tableValues: ['code', 'name', 'id'],
            displayValues: ['code', 'name'],
            values: ['id']
      });
      
      var options = {
            time: 1000,
            url: window.__CTX__.root + "/load-places/query",
            queryName: "code",
            value: ["id"],
            display: ["code", "name"]
      }
      
      $('.fromLoadPlace-search').koalaSearch(options);
      $('.toLoadPlace-search').koalaSearch(options);
      
      $(document).on("koala.search.value.changed", ".fromLoadPlace-search, .toLoadPlace-search", function(){
            console.log($(this).next().val());
            // TODO 其他查询后的逻辑
      })
      
    },
      
    initVehicle:function() {
            
      $('[data-target="#modal-search-vehicle"]').modalsearch({
        url: function(){
          var url = window.__CTX__.root + '/vehicles/query';
          return url + "?companyIds=" + $("[name='organizationId']").val();
        },
        tableColumns: ['驳运车代码', '驳运车名称'],
        tableValues: ['code', 'name'],
        displayValues: ['code', 'name'],
        values: ['id']
      });
            
      var options = {
            time: 1000,
            url: window.__CTX__.root + "/vehicles/query",
            queryName: "code",
            value: ["id"],
            display: ["code", "name"]
      }
      
      $('.vehicle-search').koalaSearch(options);
    },
      
    
    initEmployee:function() {
             
       var choseEmployees = {
          url: function(){
               var url = window.__CTX__.root + '/employees/query';
               return url + "?companyIds=" + $("[name='organizationId']").val();
            },
          tableColumns: ['员工代码', '员工名称'],
          tableValues: ['code', 'name'],
          displayValues: ['code', 'name'],
          values: ['id']
       }
       $('[data-target="#modal-search-eId"]').modalsearch(choseEmployees);
       $('[data-target="#modal-search-fId"]').modalsearch(choseEmployees);
       
       var options = {
         time: 1000,
         url: window.__CTX__.root + "/employees/query",
         queryName: "code",
         value: ["id"],
         display: ["code", "name"]
       }
     
       $('.eId-search').koalaSearch(options);
       $('.fId-search').koalaSearch(options);
       
     },
     
     triggerModalSearch: function() {
       $('.modal-search').each(function() {
         var value = $(this).val();
         console.info(value);
         if (value) {
           $(this).trigger('blur');
         }
       });
     }
  
  }
})